<template>
  <div class="home-container">
    <Skeleton v-if="showSkeleton"></Skeleton>
    <section v-else>
      <!-- 主banner区域 -->
      <section class="hero-section">
        <a-row :gutter="16" class="mb">
          <a-col :span="24" v-if="bigImage.length > 0">
            <BannerCarousel :options="bigImage" :slidesPerView="1" />
          </a-col>
        </a-row>
      </section>

      <!-- 热门推荐区域 -->
      <HotRecommend v-if="homeData.three_image.length > 0" :items="homeData.three_image" />

      <!-- 博客 -->
      <GiftSection />

      <!-- 视频或大图展示区域 -->
      <div v-if="centerImage && centerImage.length > 0" class="media-section">
        <!-- 视频播放器 -->
        <VideoPlayer v-if="isVideo(centerImage[0].image)" :videoSrc="centerImage[0].image"
          :autoplay="true" :muted="true" :loop="true" :showControls="false" :showPlayButton="true" />
        <!-- 大图展示 -->
        <div v-else class="full-width-image">
          <a :href="centerImage[0].url">
            <img :src="centerImage[0].image" :alt="centerImage[0].title || ''" />
          </a>
        </div>
      </div>

      <!-- 分类区域 -->
      <CategorySection :options="moreExploreList" />

      <!-- 我们关心的 -->
      <WeCare />

      <!-- 公司信息 -->
      <ExploreSection />

      <!-- 风格转变区域 -->
      <StyleTransform />

      <!-- 歌莉娅环游世界 下个版本需要加 -->
      <GoeliaWorld />

      <!-- 更多的 -->
      <More />

    </section>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, defineAsyncComponent, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';
import Skeleton from '@/components/Skeleton.vue';
import BannerCarousel from './components/BannerCarousel.vue';
import CategorySection from './components/CategorySection.vue';
import ExploreSection from './components/ExploreSection.vue';
import GoeliaWorld from './components/GoeliaWorld.vue';
import VideoPlayer from '@/components/VideoPlayer.vue';
import GiftSection from './components/GiftSection.vue';
import HotRecommend from './components/HotRecommend.vue';
import StyleTransform from './components/StyleTransform.vue';
import More from './components/More.vue';
import WeCare from './components/WeCare.vue';
import { getDetail } from '@/api/goods';
import { useSeo } from './hooks/useSeo.hook'

import { getHomeConfig, getHomeCategory } from "@/api/index"

import type { UploadFile } from 'ant-design-vue'

import { getSearchGoodsList } from "@/api/test.ts";
const router = useRouter();
const userStore = useUserStore();
const { proxy } = getCurrentInstance()
// 初始化SEO数据
const { seoData, pageData, initSeo } = useSeo();


let showSkeleton = ref(true);
let relatedGoods = ref<RelatedGood[]>([]);
//获取商品详情
const getDetailData = async () => {
  try {
    // const data = await getDetail(route.query.id as string);
    const data = (window as any).__INITIAL_PRODUCT__?.productdetails;
    if (!data) {
      throw new Error('No product data available');
    }
    relatedGoods.value = responseData.related_goods.map((item: any) => ({
      id: item.id,
      title: item.name,
      price: item.min_price,
      origin_price: item.min_origin_price,
      image: item.detail_images[0],
      hoverImage: item.detail_images[1],
      //判断折扣的 discount_enabled === 1 说明有折扣，则取折扣字段discount
      badge: responseData.goods_detail.discount_enabled === 1 ? `-${responseData.goods_detail.discount}% OFF` : '',
      isWishlist: responseData.goods_detail.favorite,
      inventory: responseData.goods_detail.total_stock,
    }));

  } catch (error) {
    console.error('Failed to load product details:', error);
    // message.error('Failed to load product details');
  }
}

const videoRef = ref<HTMLVideoElement | null>(null);
const moreExploreList = ref([])
const gotoShopType = (item: any) => {
  const id = item.classify_id.split("-")[1]
  // window.location.href = `/classify/${item.url.url}-${id}.html`
  router.push({
    name: 'Products',
    query: {
      classify_id: item.classify_id
    }
  })
}
const goProduct = (item: any) => {
  // window.location.href = `/classify/${item.url}-${item.category_id}.html`
  router.push({
    name: 'Products',
    query: {
      classify_id: item.classify_id
    }
  })
}
const goStory = () => {
  router.push({
    name: 'Story',
  })
}

const startPlaying = () => {
  if (videoRef.value) {
    videoRef.value.play().catch(error => {
      console.log('Auto-play was prevented:', error);
    });
  }
};

onMounted(async () => {
  if (videoRef.value) {
    videoRef.value.play().catch(error => {
      console.log('Auto-play was prevented:', error);
    });
  }
  getGoodsList()

  // 初始化SEO数据
  await initSeo('/home/data/index.json');
});

const carouselOptions = ref([
  'https://www.reiss.com/cms/resource/blob/971932/c663d02e8295173547e77815cbe0d541/dresses-data.jpg',
  'https://www.reiss.com/cms/resource/blob/971942/3e381e449b20a37b483891da538105a8/suits-and-tailoring-data.jpg',
  'https://www.reiss.com/cms/resource/blob/960878/ec532f994df8a7f69ec4444e7de896cb/petite-data.jpg',
  'https://www.reiss.com/cms/resource/blob/971934/d41b56e2015371500fee8720eea6d722/knitwear-data.jpg',
  'https://www.reiss.com/cms/resource/blob/960878/ec532f994df8a7f69ec4444e7de896cb/petite-data.jpg',
])


const goodsList = ref([

]);


// 排序方式
const sortValue = ref('1')

// 获取分类商品列表
const queryData = ref({
  page: 1,
  pageSize: 24,
  type: sortValue.value,
  goods: '',
})
const viewListTotal = ref(0)
// category分类商品
const viewList = ref([])
const getGoodsList = async () => {
  const res = await getSearchGoodsList(queryData.value)
  if (res.code === 200) {
    if (res.result.data.length > 0) {
      res.result.data.forEach((good: any) => {
        good.img = good.images.length > 0 ? good.images[0] : '';
        if (good.images.length <= 1) {
          return '';
        }
        const randomIndex = Math.floor(Math.random() * (good.images.length - 1)) + 1;
        good.imgHover = good.images[randomIndex];
      })
    }
    viewList.value = res.result.data
    viewListTotal.value = res.result.total
    goodsList.value = [];
    viewList.value.forEach((good: any) => {
      goodsList.value.push({
        image: good.images[0],
        title: good.name,
        price: good.min_price,
        ...good,
      })
    })

    // 隐藏骨架屏
    showSkeleton.value = false;
  }
}

const handleBuy = (good: any) => {
  console.log(good)
  router.push({
    path: '/details',
    query: {
      id: good.id
    }
  });
  // proxy.$push(good.url, { id: good.id })
  // router.push({
  //   path: `/product/${good.url}.html`,
  //   query: {
  //     id: good.id
  //   }
  // });
}

// const testList = ref([
//  {
//   image: 'https://www.reiss.com/cms/resource/blob/971932/c663d02e8295173547e77815cbe0d541/dresses-data.jpg',
//   title: 'Reiss Dresses',
//   price: 199,
//   url: {url: 'dresses'},
//   classify_id: "32-39"
//  }
// ])
// 获取首页接口
const homeData = ref({
  big_image: [],
  hot_recommend: [],
  three_image: [],
})
const centerImage = ref([])
const bigImage = ref([])
const getHomeData = async () => {
  // const res = await getHomeConfig();
  // homeData.value = res.result;
  homeData.value = (window as any).__INITIAL_INDEX__.homeConfig
  // if (res.code === 200) {
  // homeData.value.hot_recommend = res.result.hot_recommend;
  homeData.value.three_image.map((item: any) => {
    return {
      ...item,
      url: item.url.url
    }
  })
  homeData.value.big_image?.forEach((item: any, index: number) => {
    if (!isVideo(item.image)) {
      bigImage.value.push({
        title: item.title,
        image: item.image,
        url: item.url.url,
        classify_id: item.classify_id
      })
    } else {
      centerImage.value.push({
        title: item.title,
        image: item.image,
        url: item.url.url
      })
    }
  })
}

// 检测是否为视频
const isVideo = (src?: string): boolean => {
  if (!src) return false;
  const videoExtensions = ['.mp4', '.webm', '.ogg', '.mov', '.avi'];
  return videoExtensions.some(ext => src.toLowerCase().endsWith(ext));
};


getHomeData()
// 更多探索
const moreList = async () => {
  moreExploreList.value = (window as any).__INITIAL_INDEX__.homeCategory
  // const res = await getHomeCategory();
  // if (res.code === 200) {
  //   console.log(res.result, "阿琴的数据")
  //   moreExploreList.value = res.result
  // }
}
moreList()
</script>

<style scoped lang="scss">
// 全局风格
.home-container {
  width: 100%;
  margin: 0 auto;
  padding: 0;
  color: #232323;
  overflow-x: hidden;
}

// 区域通用样式
section {
  // padding: 0 0 60px;
  // margin-bottom: 60px;
}

.mb {
  margin-bottom: 0;
}

// 标题样式
.section-title {
  text-align: center;
  margin-bottom: 40px;
  // padding-top: 60px;

  h2 {
    font-size: 24px;
    font-weight: 500;
    letter-spacing: 2px;
    margin-bottom: 15px;
    color: #000;
  }

  .divider {
    width: 50px;
    height: 2px;
    background-color: #000;
    margin: 0 auto;
  }
}

// Hero 区域样式
.hero-section {
  margin-bottom: 50px;
  width: 100%;
}



.main-image {
  opacity: 1;
}

.hover-image {
  opacity: 0;
}

.product-image-container:hover .main-image {
  opacity: 0;
}

.product-image-container:hover .hover-image {
  opacity: 1;
}

.product-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transform: translateY(0);
  transition: opacity 0.3s ease;
  z-index: 3;
  width: 100%;
}

.product-image-container:hover .product-actions {
  opacity: 1;
}

.add-to-cart-btn {
  background-color: rgba(255, 255, 255, 0.9);
  color: #000;
  border: 1px solid #000;
  padding: 12px 0;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  border-radius: 0;
  letter-spacing: 1px;
  width: 100%;
  transition: background-color 0.3s ease, color 0.3s ease;
}

.add-to-cart-btn:hover {
  background-color: #000;
  color: #fff;
}

.wishlist-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  background-color: #fff;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s ease;
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 4;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-image-container:hover .wishlist-btn {
  opacity: 1;
}

.wishlist-btn:hover {
  background-color: #f9f1ee;
}

.product-info {
  padding: 15px 0;
}

.product-title {
  font-size: 14px;
  color: #000;
  margin-bottom: 8px;
  font-weight: 400;
  line-height: 1.4;
}

.product-price {
  font-size: 14px;
  color: #000;
  font-weight: 500;
}

/* 移动端适配 */
@media (max-width: 1024px) {
  .product-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .product-list {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }

  .tab-item {
    font-size: 14px;
    padding: 0 15px;
  }

  .product-actions {
    opacity: 1;
  }

  .add-to-cart-btn {
    padding: 10px 0;
    font-size: 11px;
  }

  .wishlist-btn {
    opacity: 1;
  }
}

@media (max-width: 480px) {
  .tab-container {
    width: 100%;
    justify-content: space-between;
  }

  .tab-item {
    padding: 0 10px;
    font-size: 12px;
  }

  .tab-item.active:after {
    left: 10px;
    right: 10px;
  }

  .product-title {
    font-size: 13px;
  }

  .product-price {
    font-size: 13px;
  }

  .badge {
    font-size: 10px;
    padding: 2px 8px;
  }
}

// 精选系列区域样式
.featured-section {
  background-color: #fff;
}

// 品牌故事区域样式
.brand-story {
  background-color: #f5f5f5;
  padding: 0 20px 80px;

  .story-content {
    max-width: 800px;
    margin: 0 auto 60px;
    text-align: center;

    p {
      font-size: 16px;
      line-height: 1.8;
      color: #555;
    }
  }

  .fabric-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
    max-width: 1200px;
    margin: 0 auto;

    .fabric-item {
      flex: 1 1 calc(25% - 30px);
      min-width: 240px;
      background-color: #fff;
      padding: 30px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);

      h3 {
        font-size: 16px;
        font-weight: 500;
        letter-spacing: 1px;
        margin-bottom: 15px;
        color: #000;
      }

      p {
        font-size: 14px;
        line-height: 1.6;
        color: #666;
      }
    }
  }

  @media (max-width: 768px) {
    .fabric-grid {
      .fabric-item {
        flex: 1 1 calc(50% - 30px);
      }
    }
  }

  @media (max-width: 576px) {
    .fabric-grid {
      .fabric-item {
        flex: 1 1 100%;
      }
    }
  }
}

.hero-video {
  width: 100%;
  height: auto;
  display: block;
}

:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-layout) {
  display: flex !important;
  flex: auto !important;
  flex-direction: column !important;
  color: rgba(0, 0, 0, 0.88) !important;
  min-height: 0 !important;
  background: #FFFFFF !important;
}

.more {
  color: #000 !important;
  font-size: 16px;
  line-height: 11px;
  text-align: center;
  letter-spacing: 0.5px;
  font-weight: 800;
  margin-top: 20px;
}

.more-title {
  padding-left: 60px;
}


.gift-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
  max-height: 874px;
  overflow: hidden;
}

.gift-grid {
  display: flex;
  gap: 30px;
}

.gift-main {
  flex: 1.5;
  position: relative;
}

.gift-grid-small {
  flex: 1.2;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 20px;
}

.image-container {
  position: relative;
  height: 100%;
  overflow: hidden;
}

.main-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  transition: transform 0.8s ease;
}

.gift-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  transition: transform 0.6s ease;
}

.gift-link {
  display: block;
  position: relative;
  height: 100%;
  overflow: hidden;
}

.gift-link:hover .main-image,
.gift-link:hover .gift-image {
  transform: scale(1.05);
}

.gift-overlay {
  position: absolute;
  bottom: 65px;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  text-align: center;
  padding: 20px;
}

.gift-text {
  max-width: 90%;
}

.gift-subtitle {
  font-size: 18px;
  font-weight: 400;
  margin-bottom: 12px;
  opacity: 0.9;
}

.gift-title {
  font-size: 42px;
  font-weight: 600;
  letter-spacing: 2px;
  margin-bottom: 0px;
}

.explore-btn {
  display: inline-block;
  padding: 10px 30px;
  border: 2px solid #fff;
  color: #fff;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  letter-spacing: 1px;
  transition: all 0.3s ease;
}

.explore-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.gift-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  color: #fff;
  padding: 15px;
  text-align: center;
}

.gift-caption h3 {
  font-size: 18px;
  font-weight: 500;
  margin: 0;
  letter-spacing: 1px;
}

.gift-item {
  position: relative;
  height: 100%;
}

/* 媒体查询 - 自适应样式 */
@media (max-width: 992px) {
  .gift-grid {
    flex-direction: column;
  }

  .gift-main {
    flex: auto;
  }

  .gift-grid-small {
    flex: auto;
  }

  .gift-title {
    font-size: 36px;
  }
}

@media (max-width: 768px) {
  .gift-grid-small {
    grid-template-columns: 1fr 1fr;
  }

  .gift-subtitle {
    font-size: 16px;
  }

  .gift-title {
    font-size: 32px;
    margin-bottom: 20px;
  }

  .gift-caption h3 {
    font-size: 14px;
  }
}

@media (max-width: 576px) {
  .gift-grid-small {
    grid-template-columns: 1fr;
  }

  .gift-title {
    font-size: 28px;
  }

  .gift-subtitle {
    font-size: 14px;
  }

  .explore-btn {
    padding: 8px 24px;
    font-size: 12px;
  }

  .gift-section {
    padding: 10px 0 40px;
  }

  .gift-grid {
    gap: 15px;
  }

  .gift-grid-small {
    gap: 15px;
  }
}

/* 媒体区域样式 */
.media-section {
  width: 100%;
  margin-bottom: 60px;
  position: relative;
  overflow: hidden;
}

.full-width-image {
  width: 100%;
  overflow: hidden;
  position: relative;
  max-height: 80vh;

}

.full-width-image img {
  width: 100%;
  height: auto;
  display: block;
  object-fit: cover;
}

/* 视频容器样式覆盖 */
:deep(.video-container) {
  max-height: 80vh;
  width: 100%;
}

:deep(.video-player) {
  width: 100%;
  height: auto;
  max-height: 80vh;
  object-fit: cover;
}

@media (max-width: 768px) {
  .media-section {
    margin-bottom: 30px;
  }

  .full-width-image,
  :deep(.video-container) {
    max-height: 50vh;
  }

  :deep(.video-player) {
    max-height: 50vh;
  }
}
</style>